<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/1/9
 * Time: 下午3:39
 */

namespace Biz\model;

use Biz\validate\GoodsSkuAttr as vGoodsSkuAttr;
use Doraemon\tools\ImgUrl as toolImgUrl;
use Medoo\Medoo;

class GoodsSkuAttr extends \Doraemon\pockets\datebase\BaseDbModel
{
    const _CONFIG_FILE_ = 'db_shop';

    const _CONFIG_SELECT_ = 'db_shop';

    const _DATABASE_ = 'shop';

    const _TABLE_NAME = 'goods_sku_attr';


    //sku ATTR状态
    const STATUS_PASSED = 1;//已审核
    const STATUS_DELETE = 9;//删除


    //支持的sku级别
    const TYPE_T1 = '1';//1级
    const TYPE_T2 = '2';//2级

    public static $typeDesc = [
        self::TYPE_T1 => 't1',//1级
        self::TYPE_T2 => 't2',//2级
    ];

    //允许通过createOrEdit操作的字段列表，进行输入转换

    protected static $fields = [
        'id',
        'type',
        'title' => ['trim', 'strip_tags'],
        'value' => ['trim', 'strip_tags'],
        'extend_info',
        'goods_id',
        'shop_id',
        'status',
    ];

    //保存商品sku Attr信息
    public static function createOrEdit($uid, $goodsId, $data, $scenes = null)
    {
        try {


            $info = self::select_master("*",
                Medoo::raw(' where goods_id=:goods_id and title=:title and `value`=:value for update', [
                    ':goods_id' => $goodsId,
                    ':title' => $data['title'],
                    ':value' => $data['value']
                ]));

            $info = array_shift($info);

            $method = !empty($info) ? 'update' : 'insert';

            if (!is_null($scenes)) {

                //提交字段进行校验
                if (!vGoodsSkuAttr::validate($data, $scenes)) {

                    $msg = vGoodsSkuAttr::firstError();

                    throw new \Exception($msg);
                }
            }

            $data = self::buidData($data);

            switch ($method) {
                case 'insert':
                    $data['shop_id'] = $uid;
                    $data['goods_id'] = $goodsId;
                    $data['addtime'] = date('Y-m-d H:i:s');


                    $ret = self::insert($data);

                    $attrId = self::id();

                    break;
                case 'update':
                    $ret = self::update($data, ['id' => $info['id']]);

                    $attrId = $info['id'];

                    break;
            }

            if ($ret->errorCode() !== '00000') {
                throw new \Exception('操作失败,请重试');
            }

            return $attrId;

        } catch (\Exception $e) {


            throw $e;
        }
    }

    public static function getList($goodsIds)
    {
        $attrs = self::select("*", ['goods_id' => $goodsIds]);

        $attrs = array_map(function ($v) {
            self::formatInfo($v);
            return $v;
        }, $attrs);

        return array_column($attrs, null, 'id');


    }

    public static function getInfo($skuAttrId)
    {
        $info = self::get("*", ['id' => $skuAttrId]);

        return $info;
    }

    public static function getSkuAttrsByGoodsIds($goodsIds)
    {
        $skuAttrs = self::select([
            'id',
            'goods_id',
            'type',
            'title',
            'value',
            'extend_info'
        ], [
            'goods_id' => $goodsIds,
            'status' => self::STATUS_PASSED
        ]);
        $formatData = [];
        foreach ($skuAttrs as $skuAttr) {
            $formatData[$skuAttr['goods_id']][$skuAttr['id']] = $skuAttr;
        }
        return $formatData;
    }

    public static function getInfoList($skuAttrIds, $is_format = false)
    {
        $infosList = self::select("*", ['id' => $skuAttrIds]);

        if ($is_format) {
            $infosList = array_map(function ($info) {
                return [
                    'id' => $info['id'],
                    'type' => $info['type'],
                    'tag' => self::$typeDesc[$info['type']],
                    'title' => $info['title'],
                    'value' => $info['value'],
                    'extend_info' => $info['extend_info'],
                    'extend_info_url' => !empty($info['extend_info']) ? toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ,
                        $info['extend_info'], toolImgUrl::IMAGE_SIZE_ORI_NPHONE) : '',
                    'extend_info_thumb_url' => !empty($info['extend_info']) ? toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ,
                        $info['extend_info'], toolImgUrl::IMAGE_SIZE_SQ_THUMB) : '',
                ];
            }, $infosList);
        }

        return array_column($infosList, null, 'id');
    }

    public static function formatInfo(&$info)
    {
        foreach ($info as $key => $value) {
            switch ($key) {
                case 'extend_info' :
                    $info['extend_info_url'] = !empty($info['extend_info']) ? toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ,
                        $info['extend_info'], toolImgUrl::IMAGE_SIZE_ORI_NPHONE) : '';
                    $info['extend_info_thumb_url'] = !empty($info['extend_info']) ? toolImgUrl::getUrl(toolImgUrl::APPTYPE_BIZ,
                        $info['extend_info'], toolImgUrl::IMAGE_SIZE_SQ_THUMB) : '';
                    break;
            }
        }
    }

}